﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using Common;
using ModelLibrary;

namespace DataBaseBackupTools.FmChild
{
    public partial class FmInstanceChild : Form
    {
        public FmInstanceChild()
        {
            InitializeComponent();
            FmInstanceChild_Load(this);
            this.cbbDatabaseType.DataSource = AppSets.DatabaseType;
            this.cbbDatabaseType.SelectedIndex = 0;
        }

        public FmInstanceChild(int IndexOfInstance)//根据序号初始化界面
        {
            InitializeComponent();
            List<Instance> LiInst = XmlHelper.XmlDeserializeFromFile<LiInstances>(AppSets.InstancePath, AppSets.Encodings);
            Instance inst = LiInst[IndexOfInstance];
            SetInstanceToApp(inst);
            ReSetIndex = IndexOfInstance;
            FmInstanceChild_Load(this);
        }

        private int ReSetIndex { get { return _ReSetIndex; } set { _ReSetIndex = value; } }
        private int _ReSetIndex = -1;
        private void btnSave_Click(object sender, EventArgs e)//保存按钮
        {
            string msg = "";
            if (this.tbTaskName.Text == "")
            {
                msg = "必须录入任务名称！";
                this.tbTaskName.Focus();
            }
            if (!testLink())
            {
                msg += msg == "" ? "链接失败，请检查链接信息！" : "\n链接失败，请检查链接信息！";
            }
            if (msg != "")
            {
                MessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //Save
            Instance inst = GetInstanceFromApp();
            inst.linkInfo = InstanceToString(inst, "shuoming");
            //XmlHelper.XmlSerializeToFile(inst, AppSetPath.InstancePath, AppSetPath.encodings);

            List<Instance> LiInst = File.Exists(AppSets.InstancePath) ? XmlHelper.XmlDeserializeFromFile<LiInstances>(AppSets.InstancePath, AppSets.Encodings) : new List<Instance>();
            if (ReSetIndex != -1)
            {
                LiInst[ReSetIndex] = inst;
            }
            else
            {
                inst.idKey = LiInst.Count;
                LiInst.Add(inst);
            }
            try
            {
                LiInstances LiInstance = new LiInstances();
                LiInstance.AddRange(LiInst);
                XmlHelper.XmlSerializeToFile(LiInstance, AppSets.InstancePath, AppSets.Encodings);
                MessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK);
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                this.DialogResult = DialogResult.None;
                throw ex;
            }

        }

        private void btnCancel_Click(object sender, EventArgs e)//取消按钮
        {
            this.Close();
        }

        private void btnTestLink_Click(object sender, EventArgs e)//测试链接按钮
        {
            string msg = testLink() ? "链接成功！" : "链接失败!";
            MessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 从界面读取实例Instance
        /// </summary>
        /// <returns>返回Instance类型</returns>
        private Instance GetInstanceFromApp()
        {
            Instance instance = new Instance();
            instance.taskName = this.tbTaskName.Text.Trim();
            instance.databaseType = this.cbbDatabaseType.Text.Trim();
            instance.address = this.tbAddress.Text.Trim();
            instance.instance = this.tbInstance.Text.Trim();
            instance.port = this.tbPort.Text.Trim();
            instance.loginName = this.tbLoginName.Text.Trim();
            instance.password = this.tbPassword.Text.Trim();
            instance.connectTimeout = this.tbConnectTimeOut.Text.Trim();
            instance.sort = this.tbSort.Text.Trim();
            instance.taskStatus = this.cbTaskStatus.Checked;
            instance.idKey = Convert.ToInt32(this.tbIdKey.Text.Trim());
            return instance;
        }
        /// <summary>
        /// 将实例instance写入到界面上
        /// </summary>
        /// <param name="instance">需要写入的instance</param>
        private void SetInstanceToApp(Instance instance)
        {
            this.tbTaskName.Text = instance.taskName;
            this.cbbDatabaseType.Text = instance.databaseType;
            this.tbAddress.Text = instance.address;
            this.tbInstance.Text = instance.instance;
            this.tbPort.Text = instance.port;
            this.tbLoginName.Text = instance.loginName;
            this.tbPassword.Text = instance.password;
            this.tbConnectTimeOut.Text = instance.connectTimeout;
            this.tbSort.Text = instance.sort;
            this.cbTaskStatus.Checked = instance.taskStatus;
            this.tbIdKey.Text = instance.idKey.ToString();
            this.richTextBox1.Text = instance.linkInfo;
        }
        /// <summary>
        /// 根据实例Instance和类型组合对应的字符串
        /// </summary>
        /// <param name="instance">实例类</param>
        /// <param name="types">取值为：sqlConnString和shuoming</param>
        /// <returns></returns>
        private string InstanceToString(Instance instance, string types)//根据实例Instance组合字符串
        {
            string s = "";
            if (types == "sqlConnString")
            {
                s = "server=" + instance.address;
                s += instance.port == "" ? "" : "," + instance.port;
                s += instance.instance == "" ? "" : "\\" + instance.instance;
                s += ";user id=" + instance.loginName + ";pwd=" + instance.password;
                s += instance.connectTimeout == "" ? "" : ";connect Timeout=" + instance.connectTimeout;
            }
            else if (types == "shuoming")
            {
                s = "地址:" + instance.address;
                s += instance.port == "" ? "" : "\n端口:" + instance.port;
                s += instance.instance == "" ? "" : "\n实例:" + instance.instance;
                s += "\n用户名:" + instance.loginName;
                s += instance.connectTimeout == "" ? "" : "\n连接超时:" + instance.connectTimeout + "秒";
            }
            return s;
        }

        private void FmInstanceChild_Load(Control ctr)//为所有TextBox添加事件
        {
            foreach (Control item in ctr.Controls)
            {
                if (item.GetType().ToString() == "System.Windows.Forms.TextBox")
                {
                    item.TextChanged += new EventHandler(TextChanged_SetShuoming);
                }
                else
                {
                    FmInstanceChild_Load(item);
                }
            }
        }
        private void TextChanged_SetShuoming(object sender, EventArgs e)//有输入字符串变动时，更新说明
        {
            this.richTextBox1.Text = InstanceToString(GetInstanceFromApp(), "shuoming");
        }

        private bool testLink()//测试链接是否成功,返回true为能链接成功
        {
            string sqlConnString = InstanceToString(GetInstanceFromApp(), "sqlConnString");
            SqlHelper sh = new SqlHelper(sqlConnString);
            return sh.connectionStatus;
        }


    }
}
